package flex.cc.store.api;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.basicinformation.dao.ValueAddedServiceProviderDao;
import flex.cc.basicinformation.entity.ValueAddedServiceProviderEntity;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.support.BaseController;
import flex.cc.drive.util.DriveDESUtil;
import flex.cc.single.service.DxVerifyService;
import flex.cc.store.dao.StoreCouponDao;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.store.dto.entity.StoreQrEntity;
import flex.cc.store.dto.vo.MsgConstant;
import flex.cc.store.service.StoreQrService;
import flex.cc.store.service.VerifyService;
import flex.cc.util.APIConfigUtil;

/**
 * 
 * @author WANGCONG
 * 2021年12月15日下午12:55:36
 * @desc 核销确认、通知接口
 */
@RestController
@RequestMapping(value = "/storeapi")
public class VerifyController extends BaseController {

	@Resource
	private VerifyService verifyService;
	@Resource
	private StoreQrService qrService;
	@Resource
	private DxVerifyService dxVerifyService;
	@Autowired
	private StoreCouponDao storeCouponDao;
	@Autowired
    private ValueAddedServiceProviderDao valueAddedserviceProviderDao;
    @Autowired
    private APIConfigUtil apiConfigUtil;
	/**
	 * 
	 * @author WANGCONG
	 * 2021年12月15日下午12:56:18
	 * @desc 核销确认（扫码后调用）
	 */
	@ResponseBody
    @RequestMapping("/verification")
    public JSONObject verify(HttpServletRequest request) throws Exception{
		JSONObject jsonResult = new JSONObject();
		String responseCode = "00";
		String responseMsg = "核销确认通过";
		long startTime = System.currentTimeMillis();
    	logger.info("VerifyController 核销确认接口:begintime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
		try {
            request.setCharacterEncoding("UTF-8");// 设置编码
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            logger.info("VerifyController 核销确认接口:reqJson="+requestJson);
            if (requestJson != null && !"".equals(requestJson)) {
            	JSONObject jsonObject = JSONObject.parseObject(requestJson);
            	String couponNum = (String)jsonObject.get("couponNum"); //卡券码
            	String carNo = (String)jsonObject.get("carNo"); //到店车牌号
//            	String createTime = (String)jsonObject.get("createTime"); //二维码生效时间
            	String scanTime = (String)jsonObject.get("scanTime"); //扫码时间
            	if(!StringUtils.isBlank(couponNum)&&!StringUtils.isBlank(carNo)&&!StringUtils.isBlank(scanTime)){
            		//根据卡券获取卡券信息  根据是否存在服务包编码 判断是否是单项类卡券
    				StoreCouponEntity storeCouponEntity = storeCouponDao.queryByCouponNum(couponNum);
    				if(PublicUtil.isEmpty(storeCouponEntity)){
    					responseCode = "01";
                    	responseMsg = "卡券码无效";
    				}else{

						Map<String, Object> params = new HashMap<String, Object>();
	            		params.put("couponNum", couponNum);
	            		StoreQrEntity qrEntity = qrService.getOneByParams(params);
	            		if(qrEntity==null){
	            			responseCode = "01";
	                    	responseMsg = "卡券码无效";
	                    	logger.error("VerifyController 卡券码无效");
	            		}else{
	            			Date createTime = qrEntity.getCreateTime(); //二维码生效时间
	            			if(qrEntity.getStatus().equals("1")){//是否已核销过，0-否，1-是
	            				responseCode = "01";
	                        	responseMsg = "卡券码已使用，请更换卡券";
	                        	logger.error("VerifyController 卡券码已使用，请更换卡券");
	            			}else{
	            				//服务包卡券
        						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                				Date endTime = sdf.parse(scanTime);
                				int seconds = DateUtil.getDateSecond(createTime, endTime);
                        		if(seconds>120){//去校验二维码的有效时间是否超过2分钟
                        			responseCode = "01";
                                	responseMsg = MsgConstant.errorQrCode;
                                	logger.error("VerifyController 二维码失效");
                        		}else{
                        			Map<String, String> resultMap = verifyService.verify(couponNum, carNo);
                        			String code = resultMap.get("code");
                        			if("01".equals(code)){
                        				responseCode = "01";
                        				responseMsg = resultMap.get("msg");
                	        		}
                        		}
	            			}
	            		}
    				}
            	}else{
            		responseCode = "01";
                	responseMsg = "请求报文参数不能为空";
                	logger.error("VerifyController 请求报文参数不能为空");
            	}
            }else {
            	responseCode = "01";
            	responseMsg = "接口处理异常:请求报文为空";
            	logger.error("VerifyController 核销确认接口---处理异常:请求报文为空");
            }
		} catch (Exception e) {
			responseCode = "01";
        	responseMsg = "数据处理异常";
        	logger.error("VerifyController 核销确认接口异常:" + e.getMessage());
		}
		jsonResult.put("responseCode", responseCode);
		jsonResult.put("responseMsg", responseMsg);
		long endTime = System.currentTimeMillis();
        logger.info("VerifyController 核销确认接口:endtime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")+"; 处理时长="+(endTime - startTime)+"; resJson=?"+jsonResult.toString());
		return jsonResult;
	}
	
	/**
	 * 
	 * @author WANGCONG
	 * 2021年12月16日下午15:32:29
	 * @desc 核销通知（接收盛大核销通知）
	 */
	/**响应示例
	 {
       "resultCode": "0000",
       "resultDesc": "成功"
     }
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping("/verifyNotice")
    public JSONObject verifyNotice(HttpServletRequest request) throws Exception{
		JSONObject jsonResult = new JSONObject();
		String responseCode = "0000";
		String responseMsg = "成功";
		long startTime = System.currentTimeMillis();
    	logger.info("VerifyController 核销通知接口:begintime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
		try {
            request.setCharacterEncoding("UTF-8");// 设置编码
            // 读取请求报文
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            logger.info("VerifyController 核销通知接口:reqJson="+requestJson);
            if (requestJson != null && !"".equals(requestJson)) {
            	JSONObject jsonObject = JSONObject.parseObject(requestJson);
            	Map<String, String> postMap = jsonObject.toJavaObject(Map.class);
            	Map<String, String> resultMap = verifyService.verifyNotice(postMap);
            	String code = resultMap.get("code");
    			if("01".equals(code)){
    				responseCode = "01";
    				responseMsg = resultMap.get("msg");
        		}
            }else {
            	responseCode = "01";
            	responseMsg = "接口处理异常:请求报文为空";
            	logger.error("VerifyController 核销通知接口---处理异常:请求报文为空");
            }
		} catch (Exception e) {
			responseCode = "01";
        	responseMsg = "数据处理异常";
        	logger.error("VerifyController 核销通知接口异常:" + e.getMessage());
		}
		jsonResult.put("resultCode", responseCode);
		jsonResult.put("resultDesc", responseMsg);
		long endTime = System.currentTimeMillis();
        logger.info("VerifyController 核销通知接口:endtime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")+"; 处理时长="+(endTime - startTime)+"; resJson="+jsonResult.toString());
		return jsonResult;
	}
	
	
}
